﻿using System;
using Core.Msg;

namespace Core.Modbus
{
    public class ModbusRxTxCommand : RxTxCommand
    {
        /// <summary>
        /// 设备地址
        /// </summary>
        public byte DevAddr { get; set; }
        /// <summary>
        /// 功能码
        /// </summary>
        public ModbusCode FunCode { get; set; }
        /// <summary>
        /// 起始寄存器地址
        /// </summary>
        public ushort RegAddr { get; set; }
        /// <summary>
        /// 读写寄存器个数
        /// </summary>
        public ushort RegNum { get; set; }
        /// <summary>
        /// 写数据（读取时不需赋值）
        /// </summary>
        public byte[] WriteData { get; set; }

        public int Type;

        /// <summary>
        /// 检查接收情况 并给ReceiveResult赋值
        /// </summary>
        public override byte[] ReceiveBytes
        {
            get => _receiveBytes;
            set
            {
                _receiveBytes = value;
                if (_receiveBytes == null || _receiveBytes.Length == 0)
                {
                    ReceiveResult = MsgResult.RecTimeout;
                }
                else if (Type == 0 && ModbusHelper.MB_NO_ERROR != ModbusHelper.CheckRecFrame(this))
                {
                    ReceiveResult = MsgResult.RecErr;
                }
                else if (Type == 1 && ModbusHelper.MB_NO_ERROR != ModbusHelper.CheckTcpRecFrame(this))
                {
                    ReceiveResult = MsgResult.RecErr;
                }
                else ReceiveResult = MsgResult.RecOk;
                RecTime = DateTime.Now;
                DealReceiveMsg?.Invoke(this, EventArgs.Empty);
                
                NotifyPropertyChanged("RecTime");
                NotifyPropertyChanged("ReceiveMsg");
                
            }
        }
        /// <summary>
        /// 对应序号(内部Modbus使用)
        /// </summary>
        public int StartIndex { get; set; }
        public ModbusRxTxCommand(string channelId,string deviceId, string strName = "普通报文", int type = 0) : base(channelId,deviceId, strName)
        {
            StartIndex = 0;
            DevAddr = 1;
            FunCode = ModbusCode.F03;
            RegAddr = 0x0000;
            RegNum = 0x0001;
            WriteData = null;
            Type = type;
            NeedReply = true;
        }
    }
}
